from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
from flask import current_app


class TokenWithItsdangerous():
    """使用itsdangerous加密解密的辅助功能类"""
    # 使用SECRET_KEY配置项作为密钥，设置过期时间为300秒
    serializer = Serializer(current_app.config['SECRET_KEY'], 300)

    @classmethod
    def generate(cls, **kwargs):
        """
        生成token
        :param kwargs: 被加密的信息
        :return: token
        """

        info = kwargs
        token = cls.serializer.dumps(info).decode()
        return token

    @classmethod
    def analysis(cls, token):
        """
        解析token
        :param token:
        :return: 被加密的信息
        """
        try:
            info = cls.serializer.loads(token)
        except SignatureExpired as e:
            current_app.logger.info(e)
            # 当token过期，返回None
            info = None
        return info
